/*
 * @Author: LiZn
 * @Date: 2021-08-21 08:10:50
 * @LastEditTime: 2021-08-22 09:17:22
 * @LastEditors: LiZn
 * @Description: 处理路由
 * @FilePath: \todaynews\src\store\permission.js
 */
import {staticRoutes,asyncRoutes} from '../router'
const staticPaths=[];
staticRoutes.forEach(route=>{
  staticPaths.push(route.path)
})
const state = {
  routes:[],//完整路由表
  addRoutes:[],//过滤出来的路由表
  routesPath:staticPaths,//将所有路由的path存成一个数组
}
const mutations = {
  setRoutes(state,routes){
    state.routes = staticRoutes.concat(routes);
    state.addRoutes  = routes;
    //清空path数组
    state.routesPath = [];
    state.routes.forEach(path=>{
      state.routesPath.push(path.path)
    })
  }
}
const actions = {
  generaterRoutes({commit},roles){
      //返回一个promise供路由守卫permission.js使用
      return new Promise(resolve=>{
        //根据用户角色获得用户可访问的路由
        const assertRoutes = filterRoutes(asyncRoutes,roles);
        commit('setRoutes',assertRoutes);
        resolve(assertRoutes);
      })
  }
}
function filterRoutes(routes,roles){
  //定义一个可以返回的路由
  let res = [];
  //这里过滤路由,路由是一个数组。用foreach处理每一条路由
  routes.forEach(route=>{
    //复制一下route
    const tmp = {...route};
    //再次判断路由中有没有用户可以访问的路由
    if(hasInterview(tmp,roles)){
      //在判断遍历中的路由中里边还有没有子路由
      if(tmp.children){
        //这里是一个递归
        tmp.children = filterRoutes(tmp.children,roles)
      }
      res.push(tmp)
    }
  })
  return res
}
function hasInterview(route,roles){
  if(route.meta&&route.meta.roles){
    return route.meta.roles.indexOf(roles)>=0
  }else{
    return true
  } 
}
export default {
  namespaced:true,
  state,
  mutations,
  actions
}